//
//  LiveContentViewController.m
//  CYWFrame
//
//  Created by Macx on 2017/8/15.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "LiveContentViewController.h"

#import "LiveCollectionViewCell.h"
//#import "LiveRoomViewController.h"
#import "LiveRoomViewControllerAudience.h"
#import "LiveRoomViewController.h"

#import "TCPlayViewController.h"
#import "TCPlayViewController_LinkMic.h"

#import "AdsServer.h"
#import "Live.h"

#import "TCLoginModel.h"
#import "TCMsgHandler.h"

@interface LiveContentViewController () <UICollectionViewDelegate, UICollectionViewDataSource,  LiveRoomVCADelegate>


@property (nonatomic, assign) NSInteger page; // 网络请求页数
@property (nonatomic, strong) NSMutableArray *infoArr;

@property (nonatomic, retain) TCPlayViewController *playVC;
@property (nonatomic, retain) LiveRoomViewControllerAudience *liveRoomVCAudience;

@property (nonatomic, strong) NSString *keyWord;
@property (nonatomic, assign) NSInteger isPush;

//AgoraLive
@property (assign, nonatomic) AgoraVideoProfile videoProfile;
@property (assign, nonatomic) AgoraClientRole clientRole;

@property (strong, nonatomic) UIImageView *backgroundImage;


@end

@implementation LiveContentViewController {
    BOOL             _hasEnterplayVC; // 直播间
    XRCarouselView  *_carouselView;
    
    UICollectionView *_collectionView;
    LiveCollectionViewCell *_item;
    
    UILabel     *_noThings;
}

- (void)viewWillAppear:(BOOL)animated {
    self.isPush = 0;
    
    if (self.isSearch) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchLive:)name:@"searchLive" object:nil];
        
    }
	else {
		[self GETLives];
	}
}

- (void)viewDidAppear:(BOOL)animated {
    _playVC = nil;
    _hasEnterplayVC = NO;
}


- (void)viewDidDisappear:(BOOL)animated {
//    [self.navigationController popViewControllerAnimated:YES];
    if (self.isSearch && self.isPush == 0) {
        [[NSNotificationCenter defaultCenter] removeObserver:self name:@"searchLive" object:nil];
    }
}

// 主页tableView是否滚动接收到通知
- (void)searchLive:(NSNotification *)notification {
    self.keyWord = notification.userInfo[@"keyWord"];
    
    NSLog(@"－－－－－直播搜索接收到通知------\n = %@", self.keyWord);
//    _noThings.hidden = YES;
    [self GETLives];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
	
	self.videoProfile = AgoraVideoProfileLandscape480P;
	self.clientRole = AgoraClientRoleAudience;
    self.keyWord = @"";
    self.page = 1;
    
    [self buildUI];
    
    if (!self.isSearch) {
        [self GETLives];
        [self GETAds];
    }
    
    
//    [self GETLives];
    
    
    
    [self refreshData];
    
}

#pragma mark ==========构建UI==========
- (void)buildUI {
    
    self.view.backgroundColor = kWhiteColor;
    
    _carouselView = [[XRCarouselView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SW(5)*2)];
//    [_scrollView addSubview:_carouselView];
    _carouselView.contentMode = UIViewContentModeScaleAspectFill;
    _carouselView.imageArray = @[IMAGE(@"img.jpg")];
    _carouselView.time = 2;
    
    
    // 集合视图 collectionView所有布局的父类
    // 系统提供自带的布局类
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    // 默认为纵向滑动
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
    
    // 创建collectionView
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 1, SCREEN_WIDTH, self.view.height-64-49-44-10) collectionViewLayout:flowLayout];
    [self.view addSubview:_collectionView];
    _collectionView.backgroundColor = kWhiteColor;
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    
    [_collectionView registerNib:[UINib nibWithNibName:@"LiveCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"item"];
    if (self.isSearch) {
        _collectionView.frame = CGRectMake(0, 1, SCREEN_WIDTH, SCREEN_HEIGHT-64-44-(1+3*SW(20)));
        flowLayout.headerReferenceSize = CGSizeMake(0, 0);
    }
	else{
		//flowLayout.headerReferenceSize = CGSizeMake(0, SW(5)*2+10);
		flowLayout.headerReferenceSize = CGSizeMake(0, 0);
	}
	
    //注册头视图
    [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionViewHeader"];
    
    
    _noThings = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-(65+SW(20)*3))];
    [self.view addSubview:_noThings];
    _noThings.text = @"没有相关资源";
    _noThings.textAlignment = NSTextAlignmentCenter;
    _noThings.backgroundColor = self.view.backgroundColor;
    _noThings.hidden = YES;

	_backgroundImage = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/2-234/2, 80, 234, 222)];
	[_backgroundImage setImage:IMAGE(@"no_job_data")];
	[_collectionView addSubview:_backgroundImage];
}

#pragma mark ==========UICollectionView==========
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    _item = [collectionView dequeueReusableCellWithReuseIdentifier:@"item" forIndexPath:indexPath];
    
    _item.model = self.infoArr[indexPath.row];
    
    return _item;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.infoArr.count;
}
//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
//    NSLog(@"%f", _item.cover.height);
    return CGSizeMake(SW(2), SW(2));
}
//定义每个UICollectionView 的 margin
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NSLog(@"点击collectionView.item = %ld", indexPath.row);
    
    Live *model = self.infoArr[indexPath.row];
    
    [self PUTLive:[model.anchor valueForKey:@"user_id"]];
    
}
//创建头视图
/*
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
           viewForSupplementaryElementOfKind:(NSString *)kind
                                 atIndexPath:(NSIndexPath *)indexPath {

    UICollectionReusableView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionViewHeader" forIndexPath:indexPath];
    if (!self.isSearch) {
        [headView addSubview:_carouselView];
    }
    headView.backgroundColor = UISeparatedColorRGB;
    
    return headView;
}
 */

#pragma mark ==========更新数据==========
- (void)refreshData {
    __weak typeof (self) weakSelf = self;
    
    _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        NSLog(@"下拉刷新");
        weakSelf.page = 1;
        [weakSelf GETLives];
    }];
    
    _collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        NSLog(@"上拉加载");
        weakSelf.page++;
        [weakSelf GETLives];
    }];
    
}


#pragma mark ===========响应方法==========
- (void)GETLives {
    
    //GET /lives 获取直播列表 ? page 页码 tag_id 分类ID per_page 每页显示数 keyword 关键词 支持直播标题
    
    NSDictionary *param;
    
    if (self.isSearch) {
        if (self.keyWord.length == 0) {
            [_collectionView.mj_header endRefreshing];
            [_collectionView.mj_footer endRefreshing];
            return;
        }
        param = @{@"page":[NSString stringWithFormat:@"%ld", self.page],
                  @"per_page":@"10",
                  @"keyword":self.keyWord};
    }
    else {
        param = @{@"page":[NSString stringWithFormat:@"%ld", self.page],
                  @"per_page":@"10",
                  @"tag_id":self.tagId};
    }
    
    [[NetworkTool sharedTool] requestWithName:@"获取直播" URLString:APILives parameters:param method:@"GET" callBack:^(id responseObject) {
        
        NSArray *arr = responseObject[@"data"];
        if (self.page == 1) {
            [self.infoArr removeAllObjects];
        }
        
        _noThings.hidden = YES;
        if (arr.count == 0) {
            self.page--;
            if (self.page == 0) {
                self.page = 1;
            }
            
            // 所有的逻辑显示
            if (self.isSearch) {
                [_collectionView.mj_footer endRefreshing];
//                [MBProgressHUD hideHUDForView:self.view animated:YES];
//                [LZCTools HUDMessage:@"没有这个直播" delay:1.5f];
                if (self.infoArr.count == 0) {
                    _noThings.hidden = NO;
                }
            }
			self.backgroundImage.hidden = NO;
        }
		else {
			self.backgroundImage.hidden = YES;
		}
        
        
        
        
        for (NSDictionary *dic in arr) {
            Live *model = [[Live alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.infoArr addObject:model];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [_collectionView.mj_header endRefreshing];
            [_collectionView.mj_footer endRefreshing];
            [_collectionView reloadData];
        });

    }];
}

// 获取广告
- (void)GETAds {
    
    [AdsServer GETAds:@{@"board":@"app_live"} xrView:_carouselView];
    
}

/**
 进入直播间
 */
- (void)PUTLive:(NSString *)userId {
    
    if (GetUserDefaule(USERINFO) == NULL) {
        [self presentViewController:[LZCTools alertMessage:@"请先登录"]animated:YES completion:nil];
        return;
    }
	[[NetworkTool sharedTool] requestWithName:@"查询主播开播状态" URLString:APICheckLiveStatus parameters:@{@"user_id":userId} method:@"GET" callBack:^(id responseObject) {
		//如果走的是成功流程才进入直播间
		// PUT /users/{uid}/lives 进入直播间 只有主播进入都会有推流地址 uid * 主播ID
		NSString *url = [APIUser stringByAppendingFormat:@"/%@/lives", userId];
		[[NetworkTool sharedTool] requestWithName:@"进入直播间" URLString:url parameters:nil method:@"PUT" callBack:^(id responseObject) {
			
			if ([[GetUserDefaule(USERINFO) valueForKey:@"user_id"] isEqualToString:userId]) {
				NSLog(@"这个直播是自己的直播，走创建直播流程");
				[LZCTools HUDMessage:@"您不能以观众身份进入自己的直播间，请点击底部\"+\"按钮重新开启直播" delay:1.0];
				/*
				// 再次检测是否已经登录？是否sig 无效
				[[TCLoginModel sharedInstance] reLogin:^{
					
					TCLiveInfo *_liveInfo;
					[MBProgressHUD hideHUDForView:self.view animated:YES];
					NSString *userId = [[TCLoginModel sharedInstance] getLoginParam].identifier;
					NSDictionary *userInfo = GetUserDefaule(USERINFO);
					NSLog(@"用户参数 = %@, %@", userInfo, userId);
					
					TCLiveInfo *publishInfo = [[TCLiveInfo alloc] init];
					publishInfo.userinfo = [[TCLiveUserInfo alloc] init];
					
					publishInfo.userinfo.nickname = userInfo[@"nickname"];
					publishInfo.userinfo.headpic = userInfo[@"face"];
					publishInfo.userinfo.frontcover = userInfo[@"face"]; // 判断什么时候上传完毕 url是否为空
					//        publishInfo.money = userInfo[@"money"];
					publishInfo.money = @"0";
					publishInfo.userid = userId;
					publishInfo.title = ((UITextField *)[self.view viewWithTag:41]).text;
					publishInfo.myuserid = userInfo[@"user_id"];
					//        publishInfo.userinfo.frontcoverImage = img.image;
					//        publishInfo.userinfo.location = ((UIButton *)[self.view viewWithTag:21]).titleLabel.text;
					
					publishInfo.tag = self.tagId;
					publishInfo.isVip = [NSString stringWithFormat:@"%@", userInfo[@"role"]];
					//        publishInfo.isLike = @"1";
					//        publishInfo.groupid
					//        publishInfo.type
					//        publishInfo.timestamp
					//        publishInfo.fileid
					
					NSDictionary *infoDict = @{@"imId":[userInfo valueForKey:@"user_id"],
											   @"uid":[userInfo valueForKey:@"user_id"],
											   @"nickname":userInfo[@"nickname"],
											   @"headpic":userInfo[@"face"],
											   @"level":[NSString stringWithFormat:@"%@", [userInfo valueForKey:@"level"]]};
					
					NSLog(@"+++++++publishInfo = %@", publishInfo);
					
					NSError *parseError = nil;
					NSData *jsonData = [NSJSONSerialization dataWithJSONObject:infoDict options:NSJSONWritingPrettyPrinted error:&parseError];
					NSString *infoStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
					
					publishInfo.senderInfo = infoStr;
					
					_liveInfo = publishInfo;
					
					// 跳转	（初步观察从该ViewController开始入手替换直播SDK，但上面也有一些附带信息需要一并替换或保留------Oldfish 2018.7.31）
					//TCPushViewController_LinkMic *pubVC = [[TCPushViewController_LinkMic alloc] initWithPublishInfo:_liveInfo];
					
					//从AgoraLive文件夹的storyboard加载出roomViewController
					UIStoryboard *agoraSB = [UIStoryboard storyboardWithName:@"AgoraLive" bundle:nil];
					LiveRoomViewController *agoraLiveRoomVC = (LiveRoomViewController *)[agoraSB instantiateViewControllerWithIdentifier:@"AgoraLiveRoomVC"];
					if (agoraLiveRoomVC) {
						agoraLiveRoomVC.clientRole = self.clientRole;
						agoraLiveRoomVC.videoProfile = self.videoProfile;
						agoraLiveRoomVC.liveInfo = _liveInfo;
						
						UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:agoraLiveRoomVC];
						
						// 设置导航背景风格颜色
						nav.navigationBar.barTintColor = UIMainColorRGB;
						[nav.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:kWhiteColor}];
						
						[self presentViewController:nav animated:YES completion:nil];
						_liveInfo = nil;
					}
					else
					{
						[HUDHelper alert:@"直播间初始化失败"];
					}
					
				} fail:^(int code, NSString *msg) {
					[MBProgressHUD hideHUDForView:self.view animated:YES];
					NSString *err = [NSString stringWithFormat:@"%@(%d)", msg, code];
					UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"登录失败"
																	message:err
																   delegate:self
														  cancelButtonTitle:@"确认"
														  otherButtonTitles:nil];
					[alert show];
				}];
				*/
			}
			else {
				Live *model = [[Live alloc] init];
				[model setValuesForKeysWithDictionary:[responseObject valueForKey:@"data"]];
				
				
				TCLiveInfo *info = [[TCLiveInfo alloc] init];
				info.userinfo = [[TCLiveUserInfo alloc] init];
				
				info.userid = [model.anchor valueForKey:@"user_id"];
				info.groupid = model.chatroom_id;
				info.likecount = [model.like_num intValue];
				info.title = model.title;
				//        info.playurl = model.pull_url[0]; // rtmp 默认第一个
				info.playurl = [model.pull_multi_urls valueForKey:@"rtmp_lsd"]; //拉流地址，键名后缀代表清晰度，无则代表原画 lud-超清 lhd-高清 lsd-标清 lld-流畅，如rtmp_lud:’rtmp://xxx’,代表超清的rtmp 默认标清，切换超清
				info.biaoUrl = [model.pull_multi_urls valueForKey:@"rtmp_lsd"];
				info.gaoUrl = [model.pull_multi_urls valueForKey:@"rtmp_lud"];
				info.timestamp = [model.start_time intValue];
				info.userinfo.nickname = [model.anchor valueForKey:@"nickname"];
				info.userinfo.headpic = [model.anchor valueForKey:@"face"];
				info.userinfo.frontcover = [model.anchor valueForKey:@"face"];
				info.isLike = [NSString stringWithFormat:@"%@", [model.anchor valueForKey:@"is_like"]];
				//        info.money = [model.anchor valueForKey:@"money"];
				info.money = [NSString stringWithFormat:@"%ld", model.stars_count];
				info.isPraise = [NSString stringWithFormat:@"%ld", model.is_like];
				
				info.viewercount = (int)model.viewer_num;
				info.roomid = [NSString stringWithFormat:@"%ld", (long)model.liveId];
				
				//        info.isVip = [self.liveData[@"anchor"] valueForKey:@"is_enterprise"];
				
				info.isVip = [NSString stringWithFormat:@"%@", [model.anchor valueForKey:@"role"]];
				info.myuserid = [model.anchor valueForKey:@"user_id"];
				
				// 保存直播信息，后面用到
				NSDictionary *live = @{@"hostId":info.userid,
									   @"groupId":info.groupid,
									   @"title":model.title,
									   @"intro":model.intro
									   };
				SetUserDefaule(live, CURRLIVE);
				NSString *isAdmin = [NSString stringWithFormat:@"%ld",model.is_admin];
				SetUserDefaule(isAdmin, SelfAdmin);
				
				NSDictionary *userinfo = GetUserDefaule(USERINFO);
				
				NSDictionary *infoDict = @{@"imId":[userinfo valueForKey:@"user_id"],
										   @"uid":[userinfo valueForKey:@"user_id"],
										   @"nickname":[userinfo valueForKey:@"nickname"],
										   @"headpic":[userinfo valueForKey:@"face"],
										   @"level":[NSString stringWithFormat:@"%@", [userinfo valueForKey:@"level"]]};
				
				
				NSError *parseError = nil;
				NSData *jsonData = [NSJSONSerialization dataWithJSONObject:infoDict options:NSJSONWritingPrettyPrinted error:&parseError];
				NSString *infoStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
				
				info.senderInfo = infoStr;
				
				// MARK: 打开播放界面
				/*
				 if (_playVC == nil) {
				 _playVC = [[TCPlayViewController_LinkMic alloc] initWithPlayInfo:info videoIsReady:^{
				 if (!_hasEnterplayVC) {
				 self.isPush = 1;
				 [self.navigationController pushViewController:_playVC animated:YES];
				 _hasEnterplayVC = YES;
				 }
				 }];
				 }
				 */
				
				if (_liveRoomVCAudience == nil) {
					UIStoryboard *agoraSB = [UIStoryboard storyboardWithName:@"AgoraLive" bundle:nil];
					_liveRoomVCAudience = (LiveRoomViewControllerAudience *)[agoraSB instantiateViewControllerWithIdentifier:@"AgoraLiveRoomVCA"];
					if (!_hasEnterplayVC && _liveRoomVCAudience) {
						self.isPush = 1;
						_liveRoomVCAudience.channelId = info.groupid;
						_liveRoomVCAudience.clientRole = self.clientRole;
						_liveRoomVCAudience.videoProfile = self.videoProfile;
						_liveRoomVCAudience.delegate = self;
						_liveRoomVCAudience.liveInfo = info;
						_hasEnterplayVC = YES;
						[self.navigationController pushViewController:_liveRoomVCAudience animated:YES];
						return;
					}
				}
				
				[self performSelector:@selector(enterPlayVC:) withObject:_liveRoomVCAudience afterDelay:0.5];
			}
		}];
	} failCallBack:^(id responseObject) {
		[self GETLives];
	}];
}

-(void)enterPlayVC:(NSObject *)obj{
    if (!_hasEnterplayVC) {
        self.isPush = 1;
        [self.navigationController pushViewController:_liveRoomVCAudience animated:YES];	//这行的VC也改了，到时候要回滚的时候记得改过来
        _hasEnterplayVC = YES;
    }
}

//MARK: - AgoraLive delegates

- (void)liveVCNeedClose:(LiveRoomViewControllerAudience *)liveVC {
	//[self dismissViewControllerAnimated:YES completion:nil];
	[self.navigationController popViewControllerAnimated:YES];
	_hasEnterplayVC = NO;
	_liveRoomVCAudience = nil;
	self.clientRole = AgoraClientRoleAudience;
}


// 懒加载
- (NSMutableArray *)infoArr {
    if (_infoArr == nil) {
        _infoArr = [[NSMutableArray alloc] init];
    }
    return _infoArr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
